//###############
//FILE : ServerInfoMessage.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
package oop.ex3.protocol.messages;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import oop.ex3.communication.SocketAddress;
import oop.ex3.exceptions.InvalidMessageException;

/**
 * This is the base class of all messages that send and receive server information in the ip/port
 * format.
 * @author daniel
 */
public abstract class ServerInfoMessage extends Message{
    String _fileManagerIp;
    int _fileManagerPort;

    /**
     * Create a new message with the specified header.
     */
    public ServerInfoMessage(String header){
        super(header);
    }

    /**
     * Create a new message with a certain header and address to send.
     * @param header The message header.
     * @param address The address to send.
     */
    public ServerInfoMessage(String header, SocketAddress address){
        super(header);
        setIp(address.getIp());
        setPort(address.getPort());
    }

    /**
     * Set the ip to send.
     * @param ip The ip.
     */
    public void setIp(String ip){
        _fileManagerIp = ip;
    }

    /**
     * Get the ip that was received. This should be called after receiving the message.
     * @return The ip string.
     */
    public String getIp(){
        return _fileManagerIp;
    }

    /**
     * Set the port to send.
     * @param port the port.
     */
    public void setPort(int port){
        _fileManagerPort = port;
    }

    /**
     * Get the port that was received. This should be called after receiving the message.
     * @return The port number.
     */
    public int getPort(){
        return _fileManagerPort;
    }

    /**
     * Get the address that was received. This should be called after receiving the message.
     * @return The socket address.
     */
    public SocketAddress getAddress() {
        return new SocketAddress(getIp(), getPort());
    }

    protected void sendDetails(DataOutputStream outputStream) throws IOException {
        outputStream.writeUTF(_fileManagerIp);
        outputStream.writeInt(_fileManagerPort);
    }

    protected void receiveDetails(DataInputStream inputStream) throws IOException, InvalidMessageException {
        _fileManagerIp = inputStream.readUTF();
        _fileManagerPort = inputStream.readInt();
    }
}
